//
//  HMNetworkTools.swift
//  3.Swift中网络的封装
//
//  Created by heima on 16/4/8.
//  Copyright © 2016年 heima. All rights reserved.
//

import UIKit
import AFNetworking

//使用结构体定义借口名称
struct API {

    //线上环境
    static let onlineHost  = "https://api.weibo.com/"
    //测试环境
    static let devHost     = "https://dev.api.weibo.com/"
    static let accessToken = "oauth2/access_token"
    static let userInfo    = "2/users/show.json"
    static let homePage    = "2/statuses/home_timeline.json"
    static let sendStatus  = "2/statuses/update.json"
    static let uploadImage =  "https://upload.api.weibo.com/2/statuses/upload.json"
}

//swift 中的枚举
enum HMHttpMethods: String {
    case POST = "POST"
    case GET = "GET"
}
class HMNetworkTools: AFHTTPSessionManager {
    //声明单例对象
    static let sharedTools: HMNetworkTools = {
        let tools = HMNetworkTools(baseURL: NSURL(string: API.onlineHost))
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return tools
    }()
    
    
}

//MARK:登录和注册相关
extension HMNetworkTools {

    func loadAccessToken(code: String, finished: (result: AnyObject?, error: NSError?) -> ()) {
    
        let parameters = ["client_id":client_id,"client_secret":client_secret,"grant_type":"authorization_code","code":code,"redirect_uri":redirect_uri]
        request(.POST, urlString: API.accessToken, parameters: parameters, finished:finished)
        
    }
    
    func loadUserInfo(token: AnyObject, uid: AnyObject,finished: (result: AnyObject?, error: NSError?) -> ()) {
    
        let parameters = ["access_token":token,"uid":uid]
        request(.GET, urlString: API.userInfo, parameters: parameters, finished: finished)
        
    }
    
}

//MARK: 首页数据相关
extension HMNetworkTools {

    func loadHomePageData(token: String,max_id: Int64,since_id: Int64, finished: (result: AnyObject?, error: NSError?) -> ()) {
    
        var parameters = ["access_token":token]
        //-1为了解决数据重复加载的问题
        //max_id初始值为0  所以不能直接-1  需要判断
        if max_id > 0 {
        parameters["max_id"]   = "\(max_id - 1)"
        }
        if since_id > 0 {
        parameters["since_id"] = "\(since_id)"
        }
        request(.GET, urlString: API.homePage, parameters: parameters, finished: finished )
    }
}

//MARK: 发布微博
extension HMNetworkTools {

    func sendStatus(token: String, status: String,imageList: [UIImage] = [UIImage](), finished: (result: AnyObject?, error: NSError?) -> ()) {
    
        let parameters = ["access_token":token, "status": status]
        if imageList.count > 0 {
        
            //发布图片微博
            //如何上传图片
            //AFN
            POST(API.uploadImage, parameters: parameters, constructingBodyWithBlock: { (formdata) -> Void in
                
//                //将要上传的二进制数据添加到formdata
//                let imageData = UIImagePNGRepresentation(imageList.first!)!
//                formdata.appendPartWithFileData(imageData, name: "pic", fileName: "heiheihei", mimeType: "image/jpeg")
                
                //上传多张图片
                for (index,image) in imageList.enumerate() {
                    let imageData = UIImagePNGRepresentation(image)!
                    formdata.appendPartWithFileData(imageData, name: "pic", fileName: "xxxxx\(index)", mimeType: "image/jpeg")
                }
                
                }, success: { (_, result) -> Void in
                    finished(result: result, error: nil)
                }, failure: { (_, error) -> Void in
                    finished(result: nil, error: error)
            })
            
        }else{
            //发布文本微博
            request(.POST, urlString: API.sendStatus, parameters: parameters, finished: finished)
        }
    }
}


//MARK:网络请求的核心方法 以后所有的get 和post 都走这个方法
extension HMNetworkTools {

    //封装所有的网络请求方法 所有的网络请求都是通过这个方法和 AFN进行联系
    func request(method: HMHttpMethods,urlString: String, parameters: AnyObject?, finished: (result: AnyObject?, error: NSError?) -> ()) {
        
        //swift中就不能够使用利用协议 欺骗Xcode
        //为了达到封装的目的 可以将相同的闭包 抽取出来,当做参数传递给AFN框架
        let success =  { (task: NSURLSessionDataTask, result: AnyObject?) -> Void in
            //执行成功的回调
            finished(result: result, error: nil)
        }
        
        //定义失败的回调
        let failure = { (task: NSURLSessionDataTask?, error: NSError) -> Void in
            //执行失败的回调
            finished(result: nil, error: error)
        }
        
        
        if method == .GET {
            GET(urlString, parameters: parameters, progress: nil, success: success, failure: failure)
        } else {
            POST(urlString, parameters: parameters, progress: nil, success: success, failure: failure)
        }
        
    }
    

    
}
